package com.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.dao.SkuInfoDao;
import com.mall.entity.*;
import com.mall.entity.Attr;
import com.mall.service.*;
import com.mall.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.dao.SpuInfoDao;
import com.mall.entity.SpuInfo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("SpuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfo> implements SpuInfoService {

    @Autowired
    private SpuInfoDao spuInfoDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Override
    public IPage<SpuInfo> listByNamePage(Integer currentPage, Integer pageSize, String spuName) {

        Page<SpuInfo> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Category> objectQueryWrapper = new QueryWrapper<>();
        String sqlSelect = objectQueryWrapper.getSqlSelect();
        QueryWrapper<Category> select = objectQueryWrapper.select(spuName);
        IPage<SpuInfo> iPage = spuInfoDao.selectPage(page, null);
//        System.out.println(select);
//        System.out.println(sqlSelect);
        return iPage;
    }

    @Override
    public IPage<SpuInfo> listByDate(Integer currentPage, Integer pageSize, String spuName) {
        List<SpuInfo> spuInfos = spuInfoDao.selectByDate(spuName);
        IPage<SpuInfo> iPage = listToPage(spuInfos, currentPage, pageSize);
//        System.out.println(iPage);
        return iPage;
    }

    @Override
    public IPage<SpuInfo> listByDesc(Integer currentPage, Integer pageSize, String spuName) {
        List<SpuInfo> list = spuInfoDao.selectByPriceDes(spuName);
        IPage<SpuInfo> iPage = listToPage(list, currentPage, pageSize);
//        System.out.println(iPage);
        return iPage;
    }

    @Override
    public IPage<SpuInfo> listByAsc(Integer currentPage, Integer pageSize, String spuName) {
        List<SpuInfo> list = spuInfoDao.selectByPriceAsc(spuName);
        IPage<SpuInfo> iPage = listToPage(list, currentPage, pageSize);
        return iPage;
    }

    @Override
    public IPage<SpuInfo> listBySales(Integer currentPage, Integer pageSize, String spuName) {
        List<SpuInfo> list = spuInfoDao.selectBySales(spuName);
        IPage<SpuInfo> iPage = listToPage(list, currentPage, pageSize);
        return iPage;
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //spu基本信息 spu_info 中有主图照片
        SpuInfo spuInfo = new SpuInfo();
        BeanUtils.copyProperties(vo,spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfo);
        //spu图片 spu概述图片
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfo.getCatId(),images);
        //spu图片集

        //spu规格参数 product_attr_value    Baseattr
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValue> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValue value = new ProductAttrValue();
            value.setAttrId(attr.getAttrId());
            Attr byId = attrService.getById(attr.getAttrId());

            value.setAttrName(byId.getAttrName());
            value.setAttrValue(attr.getAttrValues());
            value.setQuickShow(attr.getShowDesc());
            value.setSpuId(spuInfo.getId());
            return value;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);
        //spu对应信息的所有sku信息
        //sku基本信息 sku_info
        List<Skus> skus = vo.getSkus();
        if (skus!=null && skus.size()>0){
            skus.forEach(item->{
                String defaultImg="";
                for (Images image : item.getImages()) {
                    defaultImg = image.getImgUrl();
                }

                SkuInfo skuInfo = new SkuInfo();
                BeanUtils.copyProperties(item,skuInfo);
                skuInfo.setBrandId(spuInfo.getBrandId());
                skuInfo.setSaleCount(0L);
                skuInfo.setSpuId(spuInfo.getId());
                skuInfo.setSkuDefaultImg(defaultImg);

                //设置完成之后保存sku信息
                skuInfoService.saveSkuInfo(skuInfo); //保存sku信息
                //保存完成之后获取主键
                //sku图片信息 spu_images
                Long skuId = skuInfo.getSkuId();
                List<SkuImages> skuImage = item.getImages().stream().map(img -> {
                    SkuImages skuImages = new SkuImages();
                    skuImages.setSkuId(skuId);
                    skuImages.setImgUrl(img.getImgUrl());
                    skuImages.setDefaultImg(img.getDefaultImg());
                    return skuImages;
                }).filter(entity->{
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //设置完成图片信息保存
                skuImagesService.saveBatch(skuImage);


                List<com.mall.vo.Attr> attr = item.getAttr();
                List<SkuSaleAttrValue> skuSaleAttrValues = attr.stream().map(a -> {
                    SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue();
                    BeanUtils.copyProperties(a, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);
                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValues);
            });
        }


        //sku销售属性  sku_sale_attr_value

    }

    /**
     * 保存spu信息的
     * @param spuInfo
     */
    @Override
    public void saveBaseSpuInfo(SpuInfo spuInfo) {
        this.save(spuInfo);
    }


    @Override
    public void saveInfo(SpuInfoVo vo) {
        SpuInfo spuInfo = new SpuInfo();
        BigDecimal bigDecimal = new BigDecimal(Integer.MAX_VALUE);
        BeanUtils.copyProperties(vo,spuInfo);
        spuInfo.setCatId(vo.getCatalogId());
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        spuInfo.setMinPrice(bigDecimal);
        this.saveBaseSpuInfo(spuInfo);
        //spu图片 spu概述图片
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfo.getId(),images);
    }

    /**
     * 查询购买页面的数据根据spu_id
     * @param spuId
     * @return
     */
    @Override
    public List<com.mall.vo.Attr> getPurchaseBuy(Long spuId) {

        SpuInfo spuInfo = this.baseMapper.selectOne(new QueryWrapper<SpuInfo>().eq("id", spuId));

//        PurchaseVo purchaseVo = new PurchaseVo();
//        purchaseVo.setSpuName(spuInfo.getSpuName());
//        purchaseVo.setDescp(spuInfo.getDescp());

        List<SkuInfo> skuInfos = skuInfoDao.selectList(new QueryWrapper<SkuInfo>().eq("spu_id", spuInfo.getId()));
        List<com.mall.vo.Attr> list =new ArrayList<>();
        for (SkuInfo skuInfo : skuInfos) {
            //查销售属性
            List<SkuSaleAttrValue> skuSaleAttrValues = skuSaleAttrValueService.list(new QueryWrapper<SkuSaleAttrValue>().eq("sku_id", skuInfo.getSkuId()));
//            List<com.mall.vo.Attr> list =new ArrayList<>();
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValues) {
                com.mall.vo.Attr attr = new com.mall.vo.Attr();
                attr.setAttrId(skuSaleAttrValue.getId());
                attr.setAttrName(skuSaleAttrValue.getAttrName());
                attr.setAttrValue(skuSaleAttrValue.getAttrValue());
                list.add(attr);
            }

//            System.out.println(list);

        }
//        purchaseVo.setAttrs(list);
//        System.out.println(purchaseVo);
        return list;
    }






    public static IPage<SpuInfo> listToPage(List<SpuInfo> list, int pageNum, int pageSize){
        List<SpuInfo> pageList = new ArrayList<>();
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && curIdx + i < list.size(); i++) {
            pageList.add(list.get(curIdx + i));
        }
        IPage<SpuInfo> page = new Page<>(pageNum, pageSize);
        page.setRecords(pageList);
        page.setTotal(list.size());
        return page;
    }


}

/**
 * @Override
 *     public PurchaseVo getPurchaseBuy(Long spuId) {
 *
 *         SpuInfo spuInfo = this.baseMapper.selectOne(new QueryWrapper<SpuInfo>().eq("id", spuId));
 *         PurchaseVo purchaseVo = new PurchaseVo();
 *         purchaseVo.setSpu_name(spuInfo.getSpuName());
 *         purchaseVo.setDescp(spuInfo.getDescp());
 *
 *         List<PurchaseVo> purchaseVoArrayList = new ArrayList<>();
 *         List<SkuInfo> skuInfos = skuInfoDao.selectList(new QueryWrapper<SkuInfo>().eq("spu_id", spuInfo.getId()));
 *         for (SkuInfo skuInfo : skuInfos) {
 *             //查出价格
 *             //设置images
 *             List<SkuImages> skuImages = skuImagesService.list(new QueryWrapper<SkuImages>().eq("sku_id", skuInfo.getSkuId()));
 *             List<String> images = new ArrayList<>();
 *             for (SkuImages skuImage : skuImages) {
 *                 images.add(skuImage.getImgUrl());
 *             }
 *             purchaseVo.setImages(images);
 *
 *             //查销售属性
 *             List<SkuSaleAttrValue> skuSaleAttrValues = skuSaleAttrValueService.list(new QueryWrapper<SkuSaleAttrValue>().eq("sku_id", skuInfo.getSkuId()));
 *             List<com.mall.vo.Attr> list =new ArrayList<>();
 *             for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValues) {
 *                 com.mall.vo.Attr attr = new com.mall.vo.Attr();
 *                 attr.setAttrId(skuSaleAttrValue.getId());
 *                 attr.setAttrName(skuSaleAttrValue.getAttrName());
 *                 attr.setAttrValue(skuSaleAttrValue.getAttrValue());
 *                 list.add(attr);
 *             }
 *             purchaseVo.setAttrs(list);
 *             System.out.println(list);
 *
 *         }
 *         return purchaseVo;
 *     }
 */